<template>
  <div class="app-container">
    <el-collapse v-model="activeNames">
      <el-collapse-item name="1">
        <template #title>
            <div style="font-size: 15px;font-weight: 400;color: #333;"><span>条件查询</span></div>
        </template>
        <template #icon="{ isActive }">
          <div class="icon-ele">{{ isActive ? '展开' : '折叠' }}</div>
        </template>
        <div class="top-main">
          <el-row>
            <el-col :span="22">
              <el-form :model="param" :inline="true" label-width="100px">
                  <el-form-item label="箱号">
                    <MultipleBoxNumbersDialog v-model.trim="param.containerNo" clearable/>
                  </el-form-item>
                  <el-form-item label="订单号">
                    <el-input v-model.trim="param.orderNo" clearable placeholder="请输入订单号"> </el-input>
                  </el-form-item>
                  <el-form-item label="提箱城市">
                    <city-select v-model="param.boxStartCity" clearable :cityList="param.cityList" @cityId="startCityId"
                      style="width: 100%;"></city-select>
                  </el-form-item>
                  <el-form-item label="还箱城市">
                    <city-select v-model="param.boxBackCity" clearable :cityList="param.cityList" @cityId="backCityId"
                      style="width: 100%;"></city-select>
                  </el-form-item>
                  <el-form-item label="下单时间">
                    <el-date-picker v-model="param.createDate" clearable type="daterange" range-separator="~" start-placeholder="开始日期"
                      end-placeholder="结束日期" />
                  </el-form-item>
                  <el-form-item label="预计提箱日期">
                    <el-date-picker v-model="param.planPickupDate" clearable type="daterange" range-separator="~" start-placeholder="开始日期"
                      end-placeholder="结束日期" />
                  </el-form-item>
                  <el-form-item label="客户">
                    <el-input v-model.trim="param.agentName" clearable placeholder="请输入客户"> </el-input>
                  </el-form-item>
                  <el-form-item label="集装箱公司">
                    <el-input v-model.trim="param.outBoxCompanyName" clearable placeholder="请输入客户"> </el-input>
                  </el-form-item>
                  <el-form-item label="支付状态">
                    <el-select v-model="param.payStatus" clearable placeholder="请选择">
                      <el-option label="未付" value="5"></el-option>
                      <el-option label="已付" value="15"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="联系人">
                    <el-input v-model.trim="param.agentUserName" clearable placeholder="请输入联系人"> </el-input>
                  </el-form-item>
                </el-form>
            </el-col>
            <el-col :span="2">
              <el-row>
                <el-col :span="24" class="text-center"><el-button @click="handleReSet" :icon="Refresh">重置</el-button></el-col>
                <el-col :span="24" class="marginTop17 text-center"><el-button @click="getTableData" :icon="Search" type="primary">查询</el-button></el-col>
              </el-row>
            </el-col>
          </el-row>
        </div>
      </el-collapse-item>
    </el-collapse>
    <cz-tages :bottomLine="true" :typeList="typeList" @handleTypeChange="handleTypeChange" style="float: left;"></cz-tages>
    <span style="margin-top: -28px;float: right;">
      <el-dropdown placement="top" :hide-on-click="false" class="floatLeft" style="margin-right: 12px;">
        <el-button :icon="Grid" type="primary" size="small">自定义显示列</el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>
              <div class="mt-2" style="min-width: 600px;">
                <el-checkbox-group v-model="showTableItem" @change="handleGroupChange" :min="5">
                  <el-row style="width: 100%;">
                      <el-col :span="4" v-for="(item,index) in table.header"  :key="index">
                        <el-checkbox  :label="item.title" :value="item.key" size="small" />
                      </el-col>
                  </el-row>
                </el-checkbox-group>
              </div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有订单" placement="left">
        <template v-if="isSelectAll">
          <el-button :icon="Finished" size="small" @click="slectAll" plain class="floatLeft">全选</el-button>
        </template>
        <template v-else>
            <el-button size="small" @click="deselectAll" plain class="floatLeft">取消全选</el-button>
        </template>
      </el-tooltip>
      <el-button :icon="Upload" type="primary" size="small" @click="toExportBoxEastRentOrder" plain class="floatLeft">导出</el-button>
      <el-button type="primary" size="small" @click="batchDelete" plain class="floatLeft">删除</el-button>
    </span>
    <Table ref="tableRef" v-bind="table" :allId="allId" :isAllCheck="isAllCheck" @pageChange="onTablePageChange"  @deleteItem="deleteItem"  @showInfo="showInfo" @handleRefund="handleRefund"
      @handleShowContract="handleShowContract" @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox">
    </Table>

    <!-- 确认退款 -->
    <el-dialog v-model="param.dialogRefund" :with-header="false">
      <refundCard :rowData="param.rowData" :opr="'refund'"></refundCard>
    </el-dialog>
    <!-- 订单申请协议 -->
    <el-dialog v-model="param.dialogContract" :with-header="false">
      <pdfViewer :url="param.contractUrl"></pdfViewer>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import pdfViewer from '@/components/pdf'
import refundCard from '@/views/components/order/refundCard'
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
// import { getTable } from '@/api/orderManage/index.ts'
import { getTableBoxOwner as getTable } from '@/api/boxServer'
import citySelect from '@/components/citySelect'
import orderInfo from '@/store/modules/order'
import { exportBoxEastRentOrder,rentOrders } from '@/api/orderManage/index'
import { downloadFile } from '@/utils/download'
import { boxEastStatusCount } from '@/api/orderManage/index'
import { onMounted,reactive, onActivated ,ref} from 'vue';
import { Upload, Document,Finished,Refresh,Search,Grid} from '@element-plus/icons-vue'
import { useRouter, useRoute} from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus'
import MultipleBoxNumbersDialog from '@/components/dialog/multipleBoxNumbersDialog'
import {formatContainerNo} from '@/utils/mlpBox' // 格式化箱号
const router = useRouter();
const route = useRoute();
const activeNames = ref(['0'])
const showTableItem = ref<string[]>([])
const handleGroupChange = () => {
  sessionStorage.setItem(String(route.name), JSON.stringify(showTableItem.value));
  table.header.forEach(item => {
    item.isCheck = showTableItem.value.includes(item.key)
  })
}

const param = reactive({
  loading: false,
  pageNum: 1,
  pageSize: 10, // 订单状态 5-已下单|待开提箱单 10-待提未付|待提未收 15-已提未付|已提未收 20-待还未付|待还未收 25-待还已付|待还已收 30-已完成 35-已取消
  stateFilter: {
    2: '待确认',
    3: '待审核',
    5: '待开提箱单',
    10: '待提未收',
    15: '已提未收',
    20: '待还未收',
    25: '待还已收',
    28: '已还未收',
    30: '已完成',
    35: '已取消',
    40: '取消中'
  },
  // stateColor: { 5: '#22A86D', 10: '#2158F3', 15: '#2158F3' },
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '5', label: '全新', },
    { value: '10', label: '次新', },
    { value: '15', label: '适货', },
    { value: '20', label: '混提(次新或者适货)', },
  ],
  beginTotalRentQty: '',
  endTotalRentQty: '',
  boxBackCity: '',
  boxStartCity: '',
  startCityOptions: [],
  backCityOptions: [],
  refundStatusFilter: { '5': '待退款', '10': '已退款', '15': '拒绝退款', },
  invoiceStatus:"",
  agentUserName:'',
  statusType:'',
  status:'',
  payStatus:''
});

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    // { key: 'orderNo', colWidth: '200', title: '订单号', type: '<a>', command: 'showInfo', isCheck: true },
    { key: 'orderNo', key2: 'orderTypeAndRefundStatus', colWidth: '200', title: '订单号', type: '<a>', command: 'showInfo',fixed: 'left', isCheck: true },
    { key: 'carryCityName', key2: 'carryCountryName', colWidth: '100', title: '提箱城市', type: 'text',fixed: 'left', isCheck: true },
    // { key: 'returnCityName', key2: 'returnCountryName', colWidth: '100', title: '还箱城市', type: 'twoRow', isCheck: true },
    { key: 'returnCity', colWidth: '150', title: '还箱城市', type: 'moreCity', isCheck: true ,fixed: 'left',},
    { key: 'outBoxCompanyName', colWidth: '200', title: '集装箱公司', type: 'text', isCheck: true },
    { key: 'createTime', colWidth: '150', title: '下单日期', type: 'dateTime', isCheck: true },
    { key: 'planPickupDate', colWidth: '150', title: '预计提箱日期', type: 'date', isCheck: true },
    { key: 'boxType', colWidth: '70', title: '箱型', type: 'filter', filter: { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }, isCheck: true },
    { key: 'boxCondition', colWidth: '70', title: '箱况', type: 'filter', filter: { 5: '全新', 10: '次新', 15: '适货',20: '混提' }, isCheck: true },
    { key: 'boxUsagePeriod', colWidth: '70', title: '箱使期', type: 'add', after: '天', isCheck: true },
    { key: 'boxQuantity', colWidth: '100', title: '箱量', type: 'text', isCheck: true },
    { key: 'packedQuantity', colWidth: '100', title: '已提箱量', type: 'text', isCheck: true },
    { key: 'returnedQuantity', colWidth: '100', title: '已还箱量', type: 'text', isCheck: true },
    { key: 'amountCny',key2: 'amountUsd', colWidth: '120', title: '订单金额', type: 'amount', before: '￥',currency:"currency", isCheck: true },
    { key: 'status', colWidth: '120', title: '订单状态', type: 'filter',roleType:'xd',  filter: param.stateFilter, isCheck: true },
    { key: 'agentUserName', colWidth: '120', title: '联系人', type: 'text', isCheck: true },
    // { key: 'agentUserTel',key2: 'agentUserAreaCode', colWidth: '150', title: '联系电话', type: 'mobileCode',isCheck: true },
    // { key: 'invoiceNo', colWidth: '120', title: '发票号', type: 'text', isCheck: true },
    // { key: 'invoiceStatus', colWidth: '90', title: '发票状态', type: 'filter',filter: {  5:"未申请", 10:"待开票", 15:"已开票", 20:"待红冲",25:"已红冲" ,30:"已重开"}, isCheck: true },
    {
      key: 'operate',
      colWidth: '120',
      title: '订单申请协议',
      type: 'operate',
      isCheck: true,
      buttons: [
        {
          icon: Document,
          command: 'handleShowContract',
          isShow: (row) => {
            return row.downloadUrl
          },
        },
      ],
    },
    { key: 'agentName', colWidth: '200', title: '客户', type: 'text', isCheck: true },
    {
      key: 'operate',
      // colWidth: '150',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          name: '删除',
          command: 'deleteItem',
          isShow: (row) => {
            return row.status == 35   // refundStatus 5-待确认 10-已确认 15-待退款 20-已退款。
          },
        }
      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
});

const typeList =ref([
    { id: 0, name: '全部',num:0 },
    { id: 2, name: '待确认',num:0 },
    { id: 3, name: '待签署',num:0 },
    { id: 5, name: '待开提箱单',num:0 },
    { id: 10, name: '待提' ,num:0},
    { id: 15, name: '已提',num:0 },
    { id: 20, name: '未还',num:0 }, 
    { id: 25, name: '已还' ,num:0},
    { id: 30, name: '已完成',num:0 },
    { id: 35, name: '已取消' ,num:0},
    { id: 40, name: '待取消',num:0 },
])

function handleTypeChange(val: any) {
  // console.log(val)
  // param.statusType = val
  param.status = val
  getTableData()
  deselectAll()
}

//初始化
function getTableData() {
  const { container, containerList } = formatContainerNo(param.containerNo);
  let data = {
    containerNo: container, // 单箱号查询
    containerNos: containerList, // 多箱号查询
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    agentUserName: param.agentUserName || null,
    orderNo: param.orderNo|| null,
    carryCityId: param.boxStartCity,
    returnCityId: param.boxBackCity,
    // statusType: param.statusType|| null,
    status:param.status || null,
    agentName: param.agentName || null,
    outBoxCompanyName:param.outBoxCompanyName || null,
    invoiceNo: param.invoiceNo|| null,
    invoiceStatus: param.invoiceStatus,
    payStatus: param.payStatus
  }
  if (param.createDate) {
    data.beginCreateTime = param.createDate[0]
    data.endCreateTime = param.createDate[1]
  }
  if (param.planPickupDate) {
    data.beginPlanPickupDate = param.planPickupDate[0]
    data.endPlanPickupDate = param.planPickupDate[1]
  }
  table.config.loading = true;
  // 获取列表数据
  getTable(data).then(res => {
    let list = res.data.list
    table.data = list;
    table.config.total = res.data.total;
    setOrderTypeAndRefundStatus(list)
    getBoxEastStatusCount()
  });
  table.config.loading = false;
}

// 查询各状态数量
async function getBoxEastStatusCount(){
  let reqParam = {
    containerNo: param.containerNo|| null,
    containerNos: param.containerNos|| [],
    orderNo: param.orderNo|| null,
    carryCityId: param.boxStartCity,
    returnCityId: param.boxBackCity,
    beginCreateTime:'',
    endCreateTime:'',
    beginPlanPickupDate:'',
    endPlanPickupDate:'',
    agentUserName: param.agentUserName || null,
    invoiceNo: param.invoiceNo|| null,
    invoiceStatus: param.invoiceStatus,
    payStatus: param.payStatus,
    agentName: param.agentName || null,
    

  }
  if (param.createDate) {
    reqParam.beginCreateTime = param.createDate[0]
    reqParam.endCreateTime = param.createDate[1]
  }
  if (param.planPickupDate) {
    reqParam.beginPlanPickupDate = param.planPickupDate[0]
    reqParam.endPlanPickupDate = param.planPickupDate[1]
  }
  await boxEastStatusCount(reqParam).then(res => { 
    if(res.code == '00000'){
      typeList.value.forEach(item => { 
        item.num = 0
        res.data.forEach(item1 => { 
          if(item.id == 0){ //全部
            item.num += item1.totalQty
          }else if(item.id == 2 && item1.status ==2){ //待确认
              item.num += item1.totalQty
          }else if(item.id == 3 && item1.status == 3){ //待审核
              item.num += item1.totalQty
          }else if(item.id == 5 && item1.status == 5){ //待开提箱单
              item.num += item1.totalQty
          }else if(item.id == 10 && item1.status == 10 ){ //待提
              item.num += item1.totalQty
          }else if(item.id == 15 && item1.status == 15){ //已提
              item.num += item1.totalQty
          }else if(item.id == 20 && item1.status == 20){ //待还
              item.num += item1.totalQty
          }else if(item.id == 25 && item1.status == 25){ //已还
              item.num += item1.totalQty
          }else if(item.id == 30 && item1.status == 30){ //已完成
              item.num += item1.totalQty
          }else if(item.id == 40 && item1.status == 40){ //待取消
              item.num += item1.totalQty
          }else if(item.id == 35 && item1.status == 35){ //已取消
              item.num += item1.totalQty
          }else if(item.id == 45 && item1.status == 45){ //已取消
              item.num += item1.totalQty
          }
       
        });
      });
    
    }
  })
}

function setOrderTypeAndRefundStatus(list: any) {
  list.forEach((item: any) => {
    let orderType = item.orderType == 15 ? '外调' : ''
    let refundStatus = item.refundStatus ? param.refundStatusFilter[item.refundStatus] : ''
    item.orderTypeAndRefundStatus = orderType + '  ' + refundStatus
  })
}
//重置
function handleReSet() {
  param.containerNo = ''
  param.containerNos = ''
  param.orderNo = null
  param.boxStartCity = null
  param.cityList = []
  param.boxBackCity = null
  param.createDate = null
  param.planPickupDate = null
  param.agentName=null
  param.invoiceNo=null
  param.invoiceStatus=null
  param.agentUserName = ''
  param.payStatus = ''
  getTableData()
}

//查看协议
const handleShowContract = (row: any) => {
  param.dialogContract = true
  const downloadUrl = JSON.parse(row.downloadUrl)
  param.contractUrl = downloadUrl.url
}

//确认退款
const handleRefund = (row: any) => {
  param.dialogRefund = true
  param.rowData = row
}

//分页
function onTablePageChange(page) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};


//
const showInfo = (row: any) => {
  orderInfo().setRowData(row)
  // router.push('orderInfo')

  router.push({
    path:'/placingOrder/exportOrder/details',
    query:{
      orderId:row.id,
      sourceType: 'edit',
      businessRoleEnum: 10
    }
  })
}

// 删除
const deleteItem =(row: any) => { 
  ElMessageBox.confirm('确定要删除订单么？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    rentOrders([row.id]).then((res: any) => { 
      if(res.code != '00000'){
        ElMessage.warning(res.msg)
      }else{
        getTableData()
        ElMessage.success('删除成功！')
      }
    })
  }).catch(() => { });
}
//批量删除
const batchDelete = () => { 
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  const ids = checkAllItem.map((item: any) => item.id)
  ElMessageBox.confirm('确定要删除订单么？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    rentOrders(ids).then((res: any) => { 
      if(res.code != '00000'){
        ElMessage.warning(res.msg)
      }else{
        getTableData()
        ElMessage.success('删除成功！')
      }
    })
  })
}
// 城市id回写
const startCityId = (id: string) => {
  param.boxStartCity = id
}
const backCityId = (id: string) => {
  param.boxBackCity = id
}

onActivated(() => {
   if(route.query.refNo){
    param.orderNo=route.query.refNo
  }
  getTableData()
})

onMounted(()=>{
  const showTableItemStr = sessionStorage.getItem(String(route.name))
  if(sessionStorage.getItem(String(route.name))?.length && showTableItemStr){
    showTableItem.value =  JSON.parse(showTableItemStr)
  }else{
    table.header.forEach(item=>{
      showTableItem.value.push(item.key)
    })
  }
  handleGroupChange()
})

const tableRef = ref()
const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）

const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const slectAll = async(val:any) =>{
    checkAll.value = []
    let data = {
      pageNum: 1,
      pageSize: 10000,
      statusType:param.statusType || "",
    }
    await getTable(data).then(res =>{ 
      if(res.code == "00000" && res.data.list && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}


// 订单列表导出
const toExportBoxEastRentOrder = () => { 
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }


  const ids = checkAllItem.map((item: any) => item.id)
  if (ids.length < 1) return ElMessage.warning('请选择要导出的订单！')
  ElMessageBox.confirm('确认要导出选中的订单', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
        exportBoxEastRentOrder(ids).then((res: any) => {
            downloadFile(res, '订单列表详情') 
        }).catch((error) => {
            ElMessage.error(error)
        })
    }).catch(() => { });
}
</script>
<style scoped lang="scss">
// 为折叠面板图标添加样式
:deep(.el-collapse-item__header) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.icon-ele {
  flex-shrink: 0;
  padding-right: 15px;
}
</style>